import SwiftUI

struct HomeView: View {
    @StateObject private var viewModel: HomeViewModel
    
    init() {
        @Inject() var useCase: ComponentsUseCase
        _viewModel = StateObject(wrappedValue: HomeViewModel(componentsUseCase: useCase))
    }    
    
    var body: some View {
        ZStack(alignment: .top) {
            VStack {
                if viewModel.isLoading {
                    ProgressView()
                } else {
                    ScrollView {
                        VStack(spacing: 20) {
                            
                            Color.clear.frame(height: 60)
                            
                            ForEach(viewModel.components) { component in
                                switch component {
                                case HomeComponent.banner(let title):
                                    BannerView(title: title)
                                case HomeComponent.quickEntry(let items):
                                    QuickEntryGridView(items: items)
                                case HomeComponent.promotion(let title):
                                    PromotionView(title: title)
                                }
                            }
                        }
                        .padding()
                    }
                }
            }
            TopBarView()
        }
        .onAppear {
            viewModel.fetchComponents()
        }
    }
}

struct TopBarView: View {
    @State private var showingLoginView = false
    
    var body: some View {
        HStack(spacing: 15) {
            Button(action: {
                showingLoginView = true
            }) {
                Text("登录")
                    .foregroundColor(.black)
            }
            
            Spacer()
            
            Image("panda_logo")
                .resizable()
                .scaledToFit()
                .frame(height: 30)
            
            Spacer()
            
            HStack(spacing: 20) {
                Button(action: {
                    
                }) {
                    Image(systemName: "qrcode.viewfinder")
                        .foregroundColor(.black)
                }
                
                Button(action: {
                    
                }) {
                    Image(systemName: "ellipsis.message")
                        .foregroundColor(.black)
                }
            }
        }
        .padding(.horizontal)
        .frame(height: 60)
        .background(Color.white)
        .shadow(color: Color.black.opacity(0.1), radius: 5, x: 0, y: 2)
        .fullScreenCover(isPresented: $showingLoginView) {
            LoginView()
        }
    }
}
